<template>
  <el-card class="tree-card" :v-loading="loading">
    <TreeTools :data="{name:'传智教育',manager:'负责人',id:''}" :is-title="true" @add="add" />
    <el-tree :data="depts" :props="{label:'name'}" default-expand-all>
      <template #default="scope">
        <TreeTools :data="scope.data" @add="add" @edit="edit" @del="del" />
      </template>
    </el-tree>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      @close="handleClose"
    >
      <el-form ref="formRef" label-width="140px" :model="form" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model.trim="form.name" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model.trim="form.code" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <!-- <el-input v-model="form.manager" /> -->
          <el-select v-model.trim="form.manager" style="width:100%" placeholder="请选择负责人">
            <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model.trim="form.introduce" type="textarea" maxlength="300" show-word-limit />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { getDepartments, getEmployeeSimple, addEmployee, editEmployee, delEmployee } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
import TreeTools from './components/tree-tools.vue'

export default {
  components: {
    TreeTools
  },
  data() {
    const checkName = (rule, value, callback) => {
      let arr
      if (this.title === '添加子部门') {
        arr = this.depts1.filter(item => item.pid === this.node.id)
        // console.log(arr)
        // console.log(value)
      } else {
        arr = this.depts1.filter(item => item.pid === this.node.pid && item.id !== this.node.id)
        // console.log(arr)
      }
      if (arr.some(item => item.name === value)) {
        callback(new Error(`同级部门已经有${value}的部门了`))
      } else {
        callback()
      }
    }

    const checkCode = (rule, value, callback) => {
      let arr
      if (this.title === '添加子部门') {
        arr = this.depts1.filter(item => item.pid === this.node.id)
        // console.log(arr)
        // console.log(value)
      } else {
        arr = this.depts1.filter(item => item.pid === this.node.pid && item.id !== this.node.id)
        // console.log(arr)
      }
      if (arr.some(item => item.code === value)) {
        callback(new Error(`同级部门已经有${value}的编码了`))
      } else {
        callback()
      }
    }

    return {
      depts1: [],
      depts: [],
      loading: false,
      dialogVisible: false,
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      rules: {
        code: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '2-50个字符之间', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ]
      },
      employees: [],
      node: {},
      title: ''
    }
  },
  created() {
    this.getDepartments()
    this.getEmployeeSimple()
  },
  methods: {
    // 渲染数据
    async getDepartments() {
      this.loading = true
      const res = await getDepartments()
      // console.log(res)
      this.depts1 = res.depts
      this.depts = tranListToTreeData(res.depts, '')
      // console.log(this.depts)
      this.loading = false
    },
    add(node) {
      this.dialogVisible = true
      // console.log(node)
      this.node = node
      this.title = '添加子部门'
    },
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employees = res
    },
    handleClose() {
      this.$refs.formRef.resetFields()
      this.form = {}
    },
    async save() {
      try {
        await this.$refs.formRef.validate()
        if (this.title === '添加子部门') {
          this.form.pid = this.node.id
          await addEmployee(this.form)
        } else {
          await editEmployee(this.form)
        }
        this.dialogVisible = false
        this.getDepartments()
      } catch (error) {
        console.log(error)
      }
    },
    edit(node) {
      this.title = '编辑当前部门'
      this.form = { ...node }
      this.node = node
      this.dialogVisible = true
      // console.log(node)
    },
    del(id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getDepartments()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
